<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { useDesign } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';

import { Button, DatePicker, Table } from 'ant-design-vue';
import dayjs from 'dayjs';

const { prefixCls } = useDesign('cash-flow');

// 响应式数据
const loading = ref(false);
const selectedMonth = ref(dayjs('2025-01', 'YYYY-MM'));

// 表格列配置
const columns = [
  {
    title: '项目',
    dataIndex: 'project',
    key: 'project',
    width: 400,
    fixed: 'left',
  },
  {
    title: '行次',
    dataIndex: 'lineNumber',
    key: 'lineNumber',
    width: 80,
    align: 'center',
  },
  {
    title: '本月金额',
    dataIndex: 'currentMonth',
    key: 'currentMonth',
    width: 150,
    align: 'right',
  },
  {
    title: '本年累计金额',
    dataIndex: 'yearToDate',
    key: 'yearToDate',
    width: 150,
    align: 'right',
  },
];

// 原始现金流量表数据
const originalCashFlowData = [
  {
    key: 'operating-activities',
    project: '一、经营活动产生的现金流量:',
    lineNumber: '',
    currentMonth: null,
    yearToDate: null,
    level: 1,
    isGroup: true,
    hasChildren: true,
    expanded: true,
    children: [
      {
        key: 'sales-goods',
        project: '销售商品、提供劳务收到的现金',
        lineNumber: 1,
        currentMonth: 2_800_000,
        yearToDate: 2_800_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'tax-refunds',
        project: '收到的税费返还',
        lineNumber: 2,
        currentMonth: 50_000,
        yearToDate: 50_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-operating-receipts',
        project: '收到其他与经营活动有关的现金',
        lineNumber: 3,
        currentMonth: 120_000,
        yearToDate: 120_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'operating-cash-inflows',
        project: '经营活动现金流入小计',
        lineNumber: 4,
        currentMonth: 2_970_000,
        yearToDate: 2_970_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'purchase-goods',
        project: '购买商品、接受劳务支付的现金',
        lineNumber: 5,
        currentMonth: 1_800_000,
        yearToDate: 1_800_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'employee-payments',
        project: '支付给职工以及为职工支付的现金',
        lineNumber: 6,
        currentMonth: 450_000,
        yearToDate: 450_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'tax-payments',
        project: '支付的各项税费',
        lineNumber: 7,
        currentMonth: 280_000,
        yearToDate: 280_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-operating-payments',
        project: '支付其他与经营活动有关的现金',
        lineNumber: 8,
        currentMonth: 190_000,
        yearToDate: 190_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'operating-cash-outflows',
        project: '经营活动现金流出小计',
        lineNumber: 9,
        currentMonth: 2_720_000,
        yearToDate: 2_720_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'net-operating-cash-flow',
        project: '经营活动产生的现金流量净额',
        lineNumber: 10,
        currentMonth: 250_000,
        yearToDate: 250_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'investing-activities',
    project: '二、投资活动产生的现金流量:',
    lineNumber: '',
    currentMonth: null,
    yearToDate: null,
    level: 1,
    isGroup: true,
    hasChildren: true,
    expanded: true,
    children: [
      {
        key: 'investment-recovery',
        project: '收回投资收到的现金',
        lineNumber: 11,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'investment-income',
        project: '取得投资收益收到的现金',
        lineNumber: 12,
        currentMonth: 15_000,
        yearToDate: 15_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'asset-disposal',
        project: '处置固定资产、无形资产和其他长期资产收回的现金净额',
        lineNumber: 13,
        currentMonth: 25_000,
        yearToDate: 25_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-investing-receipts',
        project: '收到其他与投资活动有关的现金',
        lineNumber: 14,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'investing-cash-inflows',
        project: '投资活动现金流入小计',
        lineNumber: 15,
        currentMonth: 40_000,
        yearToDate: 40_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'fixed-asset-purchase',
        project: '购建固定资产、无形资产和其他长期资产支付的现金',
        lineNumber: 16,
        currentMonth: 180_000,
        yearToDate: 180_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'investment-payments',
        project: '投资支付的现金',
        lineNumber: 17,
        currentMonth: 50_000,
        yearToDate: 50_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-investing-payments',
        project: '支付其他与投资活动有关的现金',
        lineNumber: 18,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'investing-cash-outflows',
        project: '投资活动现金流出小计',
        lineNumber: 19,
        currentMonth: 230_000,
        yearToDate: 230_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'net-investing-cash-flow',
        project: '投资活动产生的现金流量净额',
        lineNumber: 20,
        currentMonth: -190_000,
        yearToDate: -190_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'financing-activities',
    project: '三、筹资活动产生的现金流量:',
    lineNumber: '',
    currentMonth: null,
    yearToDate: null,
    level: 1,
    isGroup: true,
    hasChildren: true,
    expanded: true,
    children: [
      {
        key: 'capital-contributions',
        project: '吸收投资收到的现金',
        lineNumber: 21,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'borrowing-receipts',
        project: '取得借款收到的现金',
        lineNumber: 22,
        currentMonth: 100_000,
        yearToDate: 100_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-financing-receipts',
        project: '收到其他与筹资活动有关的现金',
        lineNumber: 23,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'financing-cash-inflows',
        project: '筹资活动现金流入小计',
        lineNumber: 24,
        currentMonth: 100_000,
        yearToDate: 100_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'debt-repayments',
        project: '偿还债务支付的现金',
        lineNumber: 25,
        currentMonth: 80_000,
        yearToDate: 80_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'dividend-payments',
        project: '分配股利、利润或偿付利息支付的现金',
        lineNumber: 26,
        currentMonth: 30_000,
        yearToDate: 30_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'other-financing-payments',
        project: '支付其他与筹资活动有关的现金',
        lineNumber: 27,
        currentMonth: 0,
        yearToDate: 0,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'financing-cash-outflows',
        project: '筹资活动现金流出小计',
        lineNumber: 28,
        currentMonth: 110_000,
        yearToDate: 110_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
      {
        key: 'net-financing-cash-flow',
        project: '筹资活动产生的现金流量净额',
        lineNumber: 29,
        currentMonth: -10_000,
        yearToDate: -10_000,
        level: 2,
        isGroup: false,
        hasChildren: false,
        expanded: false,
      },
    ],
  },
  {
    key: 'exchange-rate-effect',
    project: '四、汇率变动对现金及现金等价物的影响',
    lineNumber: 30,
    currentMonth: 0,
    yearToDate: 0,
    level: 1,
    isGroup: false,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'net-cash-increase',
    project: '五、现金及现金等价物净增加额',
    lineNumber: 31,
    currentMonth: 50_000,
    yearToDate: 50_000,
    level: 1,
    isGroup: false,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'beginning-cash',
    project: '加：期初现金及现金等价物余额',
    lineNumber: 32,
    currentMonth: 500_000,
    yearToDate: 500_000,
    level: 1,
    isGroup: false,
    hasChildren: false,
    expanded: false,
  },
  {
    key: 'ending-cash',
    project: '六、期末现金及现金等价物余额',
    lineNumber: 33,
    currentMonth: 550_000,
    yearToDate: 550_000,
    level: 1,
    isGroup: false,
    hasChildren: false,
    expanded: false,
  },
];

// 计算表格数据（包含展开/折叠逻辑）
const tableData = computed(() => {
  const result: any[] = [];

  const processItems = (items: any[]) => {
    items.forEach((item) => {
      result.push(item);
      if (item.hasChildren && item.expanded && item.children) {
        processItems(item.children);
      }
    });
  };

  processItems(originalCashFlowData);
  return result;
});

// 切换展开/折叠
const toggleExpand = (key: string) => {
  const findAndToggle = (items: any[]): boolean => {
    for (const item of items) {
      if (item.key === key) {
        item.expanded = !item.expanded;
        return true;
      }
      if (item.children && findAndToggle(item.children)) {
        return true;
      }
    }
    return false;
  };

  findAndToggle(originalCashFlowData);
};

// 格式化金额
const formatAmount = (amount: null | number | undefined): string => {
  if (amount === null || amount === undefined) return '';
  if (amount === 0) return '0';
  const formatted = new Intl.NumberFormat('zh-CN').format(Math.abs(amount));
  return amount < 0 ? `(${formatted})` : formatted;
};

// 获取行样式类名
const getRowClassName = (record: any): string => {
  const classes = [];

  if (record.isGroup) {
    classes.push('font-semibold bg-gray-50');
  } else if (record.level === 1) {
    classes.push('font-medium');
  }

  if (
    record.project.includes('小计') ||
    record.project.includes('净额') ||
    record.project.includes('净增加额') ||
    record.project.includes('余额')
  ) {
    classes.push('bg-blue-50');
  }

  return classes.join(' ');
};

// 事件处理函数
const handlePrint = () => {
  window.print();
};

const handleDownload = () => {
  // 这里可以实现下载功能
  // eslint-disable-next-line no-console
  console.log('下载现金流量表');
};

// 初始化数据
const initData = () => {
  loading.value = true;
  // 模拟数据加载
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

onMounted(() => {
  initData();
});
</script>

<template>
  <Page
    auto-content-height
    :class="prefixCls"
    content-class="flex flex-col gap-4 p-4"
    :loading="loading"
    title="现金流量表"
  >
    <!-- 顶部信息栏 -->
    <div class="rounded-lg bg-white p-4 shadow-sm">
      <div class="mb-4 flex items-center justify-between">
        <div class="flex items-center gap-4">
          <span class="text-sm text-gray-600">编制单位：</span>
          <span class="font-medium">北京神州源科技有限公司</span>
        </div>
        <div class="flex items-center gap-4">
          <span class="text-sm text-gray-600">账期：</span>
          <DatePicker
            v-model:value="selectedMonth"
            picker="month"
            placeholder="选择月份"
            format="YYYY-MM"
            class="w-32"
          />
        </div>
        <div class="flex gap-2">
          <Button type="primary" @click="handlePrint">
            <template #icon>
              <IconifyIcon icon="lucide:printer" />
            </template>
            打印
          </Button>
          <Button type="primary" @click="handleDownload">
            <template #icon>
              <IconifyIcon icon="lucide:download" />
            </template>
            下载
          </Button>
        </div>
      </div>
    </div>

    <!-- 现金流量表表格 -->
    <div class="overflow-hidden rounded-lg bg-white shadow-sm">
      <Table
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :scroll="{ x: 1000, y: 600 }"
        size="small"
        bordered
        :row-class-name="getRowClassName"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'project'">
            <div class="flex items-center">
              <Button
                v-if="record.hasChildren"
                type="text"
                size="small"
                class="mr-2 h-4 w-4 p-0"
                @click="toggleExpand(record.key)"
              >
                <IconifyIcon
                  :icon="record.expanded ? 'lucide:minus' : 'lucide:plus'"
                  class="text-xs"
                />
              </Button>
              <span
                :class="{
                  'font-semibold': record.isGroup,
                  'font-medium': record.level === 1 && !record.isGroup,
                  'ml-4': record.level === 2,
                  'ml-8': record.level === 3,
                }"
              >
                {{ record.project }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'lineNumber'">
            {{ record.lineNumber }}
          </template>
          <template v-else-if="column.key === 'currentMonth'">
            <span class="block text-right">
              {{ formatAmount(record.currentMonth) }}
            </span>
          </template>
          <template v-else-if="column.key === 'yearToDate'">
            <span class="block text-right">
              {{ formatAmount(record.yearToDate) }}
            </span>
          </template>
        </template>
      </Table>
    </div>
  </Page>
</template>

<style scoped>
.cash-flow {
  .ant-table-thead > tr > th {
    background-color: #fafafa;
    font-weight: 600;
    text-align: center;
  }

  .ant-table-tbody > tr > td {
    padding: 8px 12px;
  }

  .ant-table-tbody > tr.bg-gray-50 > td {
    background-color: #f9fafb;
  }

  .ant-table-tbody > tr.bg-blue-50 > td {
    background-color: #eff6ff;
  }

  .ant-table-tbody > tr:hover > td {
    background-color: #f0f9ff !important;
  }
}
</style>

